package com.tianbo.elfii.client.common;

import java.io.*;
import java.net.*;
import java.sql.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.image.*;
import javax.imageio.*;

import com.tianbo.elfii.client.common.ElfiiCommonUtil.FeedBackType;

/**  <pre>
     <b>类功能描述：</b><pre>
     包含Elfii客户端运行的必要信息。
     </pre>
     @version 1.0.1
     @author 高伟 
*/

public class ElfiiCommonRunInfo {

    /** 登录时的machineId */
    private String machineId;            

    /** 登录时的用户名 */
    private String trainnerId;            

    /** 登录时的用户生日 */
    private String trainnerBirth;            

    /** 登录时的用户性别 */
    private String trainnerSex;            

    /** 数据库连接1 */
    private Connection connection1 ;      

    /** 数据库连接2 */
    private Connection connection2 ;      

    /** 八位数字 如 20120315 代表：2012年03月15日 */
    private String loginDate;             

    /** 六位时间 如 210856  代表：21点08分56秒 */
    private String loginTime;             

    /** 是否连接成功 */
    private boolean connectedOk;          

    private boolean runAsTopWindow;

    /** 程序启动时建立的窗口，因为页面里任何home按钮都需要返回此处，命名为mainFrame(主窗口) */
    private JFrame mainFrame;             

    /** 返回十四个按钮前是哪一个训练 */
    private String lastSelectedGameName;  

    public static int menuSlideButtonY;
    public static int menuLabelStartY;

    private static ElfiiCommonRunInfo runInfo=null;

    public static synchronized ElfiiCommonRunInfo getRunInfo(){
        if(runInfo==null){
            String dateStr=ElfiiCommonUtil.getLocalCurrentDate("");
            String timeStr=ElfiiCommonUtil.getLocalCurrentTime("");
            runInfo=new ElfiiCommonRunInfo ();
//            runInfo.setMachineId("123-456");
            String str;
            String fileName="elfii-common.properties";
            try {
                File f = new File(fileName);
                if (f.exists()==false){
                    FileWriter  fw = new FileWriter(fileName,true);
//                    fw.write("machine-id = 123-123\n");
                    fw.write("run-as-top-window = no\n");
                    fw.close();
                }
                FileReader fr = new FileReader(fileName);
                BufferedReader br=new BufferedReader(fr);
                while ((str=br.readLine())!=null){
//                    if (str.trim().startsWith("machine-id") && str.indexOf("=")>0){
//                        str=str.substring(str.indexOf("=")+1,str.length()).trim();
//                        runInfo.setMachineId(str);
//                    }
                    if (str.trim().startsWith("run-as-top-window") && str.indexOf("=")>0){
                        str=str.substring(str.indexOf("=")+1,str.length()).trim();
                        if (str.toLowerCase().startsWith("y"))
                            runInfo.setRunAsTopWindow(true);
                        if (str.toLowerCase().startsWith("n"))
                            runInfo.setRunAsTopWindow(false);
                    }
                }
                fr.close();
            } catch (Exception e) {System.out.println("readProperties()  "+e);}

            runInfo.setTrainnerId("");
            runInfo.setLoginDate(dateStr);
            runInfo.setLoginTime(timeStr);
        }
        return runInfo;
    } 

    public void setRunAsTopWindow(boolean b){
        runAsTopWindow=b;
    }

    public boolean isRunAsTopWindow(){
        return runAsTopWindow;
    }//auto

    public void setMachineId(String machineId){
        this.machineId=machineId;
    } 
    public String getMachineId(){
        return machineId;
    }

    public void setTrainnerId(String trainnerId){
        this.trainnerId=trainnerId;
    }
    public String getTrainnerId(){
        return trainnerId;
    }
 
    public void setTrainnerSex(String trainnerSex){
        this.trainnerSex=trainnerSex;
    }
    public String getTrainnerSex(){
        return trainnerSex;
    }

    public void setTrainnerBirth(String trainnerBirth){
        this.trainnerBirth=trainnerBirth;
    }
    public String getTrainnerBirth(){
        return trainnerBirth;
    }
 
    public void setLastSelectedGameName(String lastSelectedGameName){
        this.lastSelectedGameName=lastSelectedGameName;
    }

    public void setLoginTime(String loginTime){
        this.loginTime=loginTime;
    }

    public void setLoginDate(String loginDate){
        this.loginDate=loginDate;
    }

    public void setMainFrame(JFrame mainFrame){
        this.mainFrame=mainFrame;
    }
    public JFrame getMainFrame(){
        return mainFrame;
    }

    public ElfiiCommonRunInfo() {
        connectedOk=false;
    }

    public boolean isConnectedOk(){
        return connectedOk;
    }

    public Statement getStatement1(){
        Statement statement1=null;
        try {
            statement1 = connection1.createStatement();
        } catch (Exception e) {System.out.println("init()  "+e);}
        return statement1;
    }
    public Statement getStatement2(){
        Statement statement2=null;
        try {
            statement2 = connection2.createStatement();
        } catch (Exception e) {System.out.println("init()  "+e);}
        return statement2;
    }

    public Connection getConnection1(){
        return connection1;
    }
    public Connection getConnection2(){
        return connection2;
    }
 
    public String getLoginTime(){
        return loginTime;
    }
 
    public String getLoginDate(){
        return loginDate;
    }

    public void initJdbc()  {
        connectedOk=false;
        try {
            long startTimeMillis=System.currentTimeMillis();
            Class.forName("com.mysql.jdbc.Driver");
            connection1=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/elfiidatabase?characterEncoding=utf-8","root","root");
            connection2=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/elfiidatabase?characterEncoding=utf-8","root","root");
            loginDate=ElfiiCommonUtil.getLocalCurrentDate("");
            loginTime=ElfiiCommonUtil.getLocalCurrentTime("");
            connectedOk=true;

            Statement statement1 = connection1.createStatement();

            String str;
            str="create table if not exists TrainningLogin (Id int(10) unsigned not null auto_increment,primary key (Id),machineID char(20) not null default '',trainnerID char(30) not null default '',loginDate char(8) not null default '',loginTime	nchar(6) not null default '',IsUpload numeric(1) not null default 0) engine=INNODB DEFAULT CHARSET=utf8";
            statement1.execute(str);
            str="create table if not exists TrainningUser (Id int(10) unsigned not null auto_increment,primary key (Id),machineID char(20) not null default '',trainnerID char(30) not null default '',sex char(5) not null default '',birth	nchar(10) not null default '',lastLoginDate char(8) not null default '',lastLoginTime	nchar(6) not null default '',IsUpload numeric(1) not null default 0) engine=INNODB DEFAULT CHARSET=utf8";
            statement1.execute(str);
            str="create table if not exists TrainningDeletedUser (Id int(10) unsigned not null auto_increment,primary key (Id),machineID char(20) not null default '',trainnerID char(30) not null default '',sex char(5) not null default '',birth	nchar(10) not null default '',lastLoginDate char(8) not null default '',lastLoginTime	nchar(6) not null default '',IsUpload numeric(1) not null default 0) engine=INNODB DEFAULT CHARSET=utf8";
            statement1.execute(str);

            str="create table if not exists TrainningItemAPO (Id int(10) unsigned not null auto_increment,primary key (Id),machineID char(20) not null default '',trainnerID char(20),trainningTitle char(30) not null default '',trainningDate char(8) not null default '',trainningTime	nchar(6) not null default '',trainningItemLevel numeric(1) not null default 0,trainningItemNumber	numeric(1),testTotalSeconds numeric(3) not null default 0,costTotalSeconds numeric(3) not null default 0,currentTrainingCompleted char(5) not null default '',topicQuantity numeric(2) not null default 0,trainningResultInfo Varchar(30) not null default '',memoryUnitNumber numeric(2) not null default 0,actionLimitTime numeric(3) not null default 0,testCompletedRate numeric(6,3) not null default 0,testCorrectRate numeric(6,3) not null default 0,historyCompletedRate numeric(6,3) not null default 0,historyCorrectRate numeric(6,3) not null default 0,IsUpload numeric(1) not null default 0, pdbz int(10), bz int(10) ) engine=INNODB DEFAULT CHARSET=utf8";
            statement1.execute(str);
            str="create table if not exists TrainningItemAProduceTopicPO (Id int(10) unsigned not null auto_increment,primary key (Id),machineID char(20) not null default '',actionResult char(20) not null default '',section int(2), actionCostTime int(8) not null default 0,id_TrainningItemAPO int(10),IsUpload numeric(1) not null default 0 , key (id_TrainningItemAPO) )  engine=INNODB DEFAULT CHARSET=utf8";
            statement1.execute(str);

            long endTimeMillis=System.currentTimeMillis();
            //System.out.println("\n\nMySQL Connection Ok, Time:(1/1000) "+(endTimeMillis-startTimeMillis));
            System.out.println("\n\nELFII客户端启动，MySQL Connection Ok。");
        } catch (Exception e) {System.out.println("init()  "+e);}
    }

    public JButton createHomeButton() {
        
        ImageIcon homeIcon = new ImageIcon("resource-common/images/btn-home.png","");
        JButton homeButton=new JButton();
        homeButton.setBackground(Color.white);
        homeButton.setBorderPainted(false);
        homeButton.setFocusPainted(false);
        homeButton.setIcon(homeIcon);
        homeButton.setModel(new DefaultButtonModel() {
                public boolean isPressed(){
                    return false; 
                }
            }
            ) ;
        homeButton.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //System.exit(0); 
                    goBackHome();
                    ElfiiCommonUtil.playFeedbackAudio(FeedBackType.CLICK);
                }
            });

        return homeButton;
    }

    public void goBackGameSelect(){

        mainFrame.getContentPane().removeAll();
        mainFrame.getContentPane().setLayout(new BorderLayout());
        ElfiiCommonGameSelect gameSelect = new ElfiiCommonGameSelect();
        gameSelect.setLastSelectedGameName(lastSelectedGameName);
        gameSelect.setRunInfo(runInfo);
        mainFrame.getContentPane().add(gameSelect.createViewPanel(),BorderLayout.CENTER);
        mainFrame.setVisible(true);
    }

    public void goBackHome(){
        mainFrame.getContentPane().removeAll();
        mainFrame.getContentPane().setLayout(new BorderLayout());
        ElfiiCommonWelcome welcome = new ElfiiCommonWelcome();
        welcome.setRunInfo(runInfo);
        mainFrame.getContentPane().add(welcome.createViewPanel(),BorderLayout.CENTER);
        mainFrame.setVisible(true);
    }

    public static void main(String[] args)    {
        ElfiiCommonRunInfo runInfo=new ElfiiCommonRunInfo();
        runInfo.initJdbc();
        System.out.println("是否连接成功："+runInfo.isConnectedOk());
        System.out.println("连接日期："+runInfo.getLoginDate());
        System.out.println("连接时间："+runInfo.getLoginTime());
   }

}
